const http = require('http')

const server = http.createServer((req, res) => {})

server.on('request', (req, res) => {
  console.log('Request received')

  console.log('------ METHOD: ------')
  console.log(req.method)

  console.log('------ URL: ------')
  console.log(req.url)

  console.log('------ HEADERS: ------')
  console.log(req.headers)
  const name = req.headers.name

  console.log('------ BODY: ------')
  let body = []
  req
    .on('data', (chunk) => {
      body.push(chunk)
    })
    .on('end', () => {
      try {
        body = JSON.parse(Buffer.concat(body).toString())
        console.log(body)
        console.log(name)

        res.writeHead(200, { ContentType: 'application/json' })
        res.end(
          JSON.stringify({
            message: `The post with title ${body.title} created by ${name} was saved successfully.`,
          }),
        )
      } catch (error) {
        console.error('Error processing request body:', error)
        res.statusCode = 500
        res.end('Internal Server Error')
      }
    })
})

server.listen(3000, () => {
  console.log('Server is running on port 3000')
})
